todayStr() and nowStr() Functions

These functions display the current date and time in familiar mm/dd/yyyy and hh:mm AM/PM formats. The current date and time are determined by the client PC's system clock. The values returned by these functions are strings, not date objects. So you can't do any date arithmetic with those values. To use today() or now() in a web page, paste either, or both, of the functions shown below into your page, anywhere between the <head>...</head> tags:

<script language="JavaScript">
//--Returns the current system time as a string in hh:mm am/pm format.
function nowStr() {
   var now=new Date()
   var hours=now.getHours()
   var minutes=now.getMinutes()
   timeStr=""+((hours > 12) ? hours - 12 : hours)
   timeStr+=((minutes < 10) ? ":0" : ":") + minutes
   timeStr+=(hours >= 12) ? " PM" : " AM"
   return timeStr
}

//--Returns the current date in mm/dd/yy format as a string.
function todayStr() {
   var today=new Date()
   return today.getMonth()+1+"/"+today.getDate()+"/"+today.getYear()
}
</script>

Examples

Once those scripts are in your page, you can use the function name alone (with parentheses) to display the current date or time in your web page, as in the examples below:

<!-- Lines below use document.write() to put date/time into body text -->
<p>Today is <script>document.write(todayStr())</script>.<br>
The time is <script>document.write(nowStr())</script>.</p>

<!-- Script near bottom of page puts date/time into read-only form fields -->
<form name="myForm">
  Today is:&nbsp;<input name='date' onfocus='this.blur()'><br>
  Time is:&nbsp;<input name='time' onfocus='this.blur()'><br>
</form>

<script language="JavaScript">
   //-- This script must be executed after form has been rendered,
   //-- because it puts its date and time into the form's fields.
   document.myForm.date.value=todayStr()
   document.myForm.time.value=nowStr()
</script>

The results, in a web page, look like this:

Today is .
The time is .

Today is: 
Time is: 

 

Tip: For graphical and running clocks, see my JavaScript Clock examples

Top   More Date Functions   JavaScript Examples   Coolnerds home